/*
 *     This file is part of Mobile GPS Logger.
 *
 *     Mobile GPS Logger is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Mobile GPS Logger is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License v3 for more details.
 *
 *     You should have received a copy of the GNU General Public License v3
 *     along with Mobile GPS Logger. If not, see <http://www.gnu.org/licenses/>.
 */

package cx.ath.skyflyer.gpslog.nmea;

import cx.ath.skyflyer.gpslog.util.Tokenizer;
import java.util.NoSuchElementException;

/**
 *
 * @author Ahti Legonkov
 */
public class GeographicPosition extends NmeaSentence {

    public static final String PREFIX = "$GPGLL";

    public GeographicPosition(String gpgll) throws ChecksumMismatchException {
        super(gpgll);

        Tokenizer a = new Tokenizer(gpgll, new char[] {'*'});
        String s = a.next();
        if (a.hasNext()) {
            String checksum = a.next();
            // TODO: check the checksum?
        }

        parser = new Tokenizer(s, new char[] {','});
        String id = parser.next();
        if (!id.equals(PREFIX)) {
            throw new UnsupportedTypeException(id, PREFIX);
        }
    }

    public String getLatitude() {
        if (latitude == null)
            parse();

        return latitude;
    }

    public boolean isNorth() {
        parse();
        return north;
    }

    public String getLongitude() {
        if (longitude == null)
            parse();

        return longitude;
    }

    public boolean isEast() {
        parse();
        return east;
    }

    public String getTime() {
        if (time == null)
            parse();

        return time;
    }

    public static GeographicPosition parse(String nmea) {
        try {
            GeographicPosition res = new GeographicPosition(nmea);
            return res;
        }
        catch (Exception ex) {
            return null;
        }
    }

    private void parse() {

        if (parser == null)
            return;

        latitude = parser.next();
        String n = parser.next();
        north = n.equals("N");

        longitude = parser.next();
        String e = parser.next();
        east = e.equals("E");

        try {
            // time may be missing from the sentence.
            time = parser.next();
        }
        catch (NoSuchElementException ex) {
            time = "";
        }

        // don't need that anymore.
        parser = null;
    }

    private Tokenizer parser;

    private String latitude;
    private boolean north;
    private String longitude;
    private boolean east;
    private String time;
}
